package org.wxd.ms.stu.consumer.web;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by wangxd on 2017/6/9.
 */
@RestController
public class UserCtl {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserCtl.class);

    @Autowired
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;
    @Resource
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private UserFeignClient feignClient;


    // 请求这里的隔离，并非feign的隔离,如果移除该配置，则会返回feign配置的隔离
    @HystrixCommand(fallbackMethod = "findByIdFallback")
    @GetMapping("/user/{id}")
    public User findById(@PathVariable Long id){
        LOGGER.info("the user id is [{}]",id);
//        return restTemplate.getForObject("http://localhost:8080/user/" + id,User.class);
        // 负载均衡实现
//        return restTemplate.getForObject("http://stu-service/user/" + id,User.class);
        // feign实现
        return feignClient.findById(id);
    }


    public User findByIdFallback(Long id){
        User user = new User();
        user.setId(id);
        user.setName("default");
        user.setAddr("default-addr");
        user.setAge(1000);
        return user;
    }




    /**
     * 查询服务信息
     * @return
     */
    @GetMapping("/user-instance")
    public List<ServiceInstance> showInfo(){
        return this.discoveryClient.getInstances("stu-service");
    }

    @GetMapping("/log-instance")
    public void logInstance(){
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("stu-service");

        LOGGER.info("{}:{}:{}",serviceInstance.getServiceId(),serviceInstance.getHost(),serviceInstance.getPort());
    }




}
